import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { UserLabelAddComponent } from '../../../sharedModule/commponent/user-label-add/user-label-add.component';
import { CustomerMerchantService } from './customer-merchant.service';
import { OrderAccService } from '../../order/order-acc/order-acc.service'
import {PermissionService} from '../../../service/permission.service';
@Component({
    selector: 'app-customer-merchant',
    templateUrl: './customer-merchant.component.html',
    styleUrls: ['./customer-merchant.component.scss']
})
export class CustomerMerchantComponent implements OnInit {
    @ViewChild('fansModal') fansModal: any;

    isCollapse: boolean = false;
    isVisible = false;

    /**
     * 列表数据源
     */
    listOfData?: any;
    /**
     * 查询参数格式
     */
    queryForm: any = {
        // 综合搜索
        user: '',
        //ID
        userId: '',
        // 昵称
        name: '',
        // 电话
        phone: '',
        // 账号状态
        status: '',
        //用户初始身份
        temUserType: '',
        //用户真实身份
        userType: '',
        // 开始时间
        beginTime: '',
        // 结束时间
        endTime: '',
        // 时间区间
        dateFormat: '',

        //0 表示userId查询 1表示id查询
        type: '0',
        page: 1,
        pageSize: 20,
    }
    /**
     * 跟进参数
     */
    followParam: any = {
        // 关联信息(订单号 售后单号 客户id 出库单号)
        relationInformation: "",
        // 1、订单 2、售后 3、客户 4、出库
        type: 3,
        // 文件列表
        enclosure: [],
        // 备注
        content: "",
        // 当前页
        page: 1,
        // 当天加载条数
        pageSize: 10
    }

    /**
     * 全局 loading
     */
    messageId: any = null;
    /**
     * 表单load加载
     */
    tableLoading: any = false;
    /**
     * 当前是否在搜索
     */
    searchHint = false;
    // 跟进弹窗
    followVisible: boolean = false
    /**
     * 当前搜索name
     */
    searcName = "";
    // 弹窗 跟进记录
    modalTable: any = {
        // 列表集合
        records: [],
        // 总条数
        total: 0
    }
    /**
     * 上传val
     */
    inputVal: any = null;

    // 粉丝
    fansItems: any = {};

    constructor(
        private message: NzMessageService,
        private CustomerMerchantService: CustomerMerchantService,
        private OrderAccService: OrderAccService,
        public permission: PermissionService,
        private nzModalService: NzModalService
    ) { }

    ngOnInit() {
        this.getCustomerList();
    }

    showModal(): void {
        this.isVisible = true;
    }

    handleCancel() {
        this.isVisible = false;
        this.followVisible = false
        this.followParam.relationInformation = '';
    }
    query() {
        this.getCustomerList();
    }

    // 重置
    resetData() {
        this.queryForm.user = '';
        this.queryForm.userId = '';
        this.queryForm.name = '';
        this.queryForm.phone = '';
        this.queryForm.status = '';
        this.queryForm.temUserType = '';
        this.queryForm.userType = '';
        this.queryForm.dateFormat = '';

        this.queryForm.page = 1;
        this.getCustomerList();
    }

    /**
     * 刷新列表
     */
    refresh() {
        this.listOfData = [];
        this.getCustomerList();
    }
    /**
     * 页码改变
     * @param index 页码数
     */
    onPageIndexChange(index: Number) {
        this.queryForm.page = index;
        this.getCustomerList();
    }
    /**
     * 每页条数改变的回调
     * @param index 页码数
     */
    onPageSizeChange(index: Number) {
        this.queryForm.pageSize = index;
        this.getCustomerList();
    }
    /**
     * 搜索返回原列表
     */
    backList() {
        // this.queryForm.user = "";
        this.queryForm.userId = "";
        this.queryForm.name = "";
        this.queryForm.phone = "";
        this.queryForm.status = "";
        this.queryForm.temUserType = "";
        this.queryForm.userType = "";
        this.queryForm.dateFormat = "";

        this.queryForm.page = 1;
        this.searchHint = false;
        this.getCustomerList();
    }


    /**
     * 复制内容
     */
    copy(val: any) {
        let oInput = document.createElement('input');
        oInput.value = val;
        document.body.appendChild(oInput);
        oInput.select();
        document.execCommand('Copy');
        document.body.removeChild(oInput);
        this.createMessage('success', "复制成功");
    }


    /**
     * 客户管理列表
     */
    getCustomerList() {
        if (this.tableLoading) { return; }
        this.listOfData = [];
        this.tableLoading = true;
        this.CustomerMerchantService.getList(this.queryForm).subscribe((res: any) => {
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            let textArr = [];
            // if (this.queryForm.user) {
            //     textArr.push(this.queryForm.user);
            // }
            if (this.queryForm.userId) {
                textArr.push(this.queryForm.userId);
            }
            if (this.queryForm.name) {
                textArr.push(this.queryForm.name);
            }
            if (this.queryForm.phone) {
                textArr.push(this.queryForm.phone);
            }

            if (this.queryForm.status) {
                textArr.push(this.state_To_text(this.queryForm.status));
            }
            if (this.queryForm.temUserType) {
                textArr.push(this.temUserType_To_text(this.queryForm.temUserType));
            }
            if (this.queryForm.userType) {
                textArr.push(this.userType_To_text(this.queryForm.userType));
            }
            if (this.queryForm.dateFormat) {
                let strTime = this.CustomerMerchantService.shiftDate(this.queryForm.dateFormat[0]);
                let endTime = this.CustomerMerchantService.shiftDate(this.queryForm.dateFormat[1]);
                let time = strTime + " - " + endTime;
                textArr.push(time);
            }
            this.searcName = textArr.join(' | ');

            this.listOfData = res.data;
            for (let index = 0; index < this.listOfData.list.length; index++) {
                const element = this.listOfData.list[index];
                element.statusText = this.state_To_text(element.status);
                element.temUserTypeText = this.temUserType_To_text(element.temUserType);
            }
            this.tableLoading = false;
        }, err => {
            this.tableLoading = false;
            this.createMessage("error", err.message);
        })
    }
    /**
   * 删除跟进图片
   */
    deleteFollowImg(index: any) {
        this.inputVal = null;
        this.followParam.enclosure = this.followParam.enclosure.filter((item: any, i: any) => {
            return i != index;
        });
    }
    /**
     * 打开模态框(跟进) 初始化
     * @param id
     */
    followModal(relationInformation: any): void {
        this.followParam.relationInformation = relationInformation;
        this.followParam.enclosure = []
        this.followParam.content = ''
        this.followVisible = true;

    }
    /**
      * 上传文件
      * @param su 上传完成回调函数
      */
    postFile(file: any, su: any) {
        this.OrderAccService.postFile(file).subscribe(data => {
            if (su) su(data);
        }, error => {

        });
    }
    /**
  * 只保留文件名加后缀
  */
    formUrl(url: String) {
        return url.substr(url.lastIndexOf('/') + 1);
    }
    /**
   * 新增跟进
   */
    followerSave() {
        if (this.messageId != null) {
            return;
        }
        if (!this.followParam.content) {
            return this.createMessage("warning", "请输入备注");
        }
        this.createBasicMessage();
        this.OrderAccService.followerSave(this.followParam).subscribe((res: any) => {
            this.removeBasicMessage();
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.handleCancel();
            this.createMessage("success", "跟进信息成功");
        }, err => {
            this.removeBasicMessage();
            this.createMessage("error", err.message);
        })
    }

    /**
       * 文件上传完成回调
       * @param files
       * @param type  1:图片信息 2:视频文件 3:视频封面
       */
    handleFileInput(files: any, type: any) {
        let fileArr = files.target.files;
        for (let index = 0; index < fileArr.length; index++) {
            const element = fileArr[index];
            this.postFile(element, (res: any) => {
                if (res.code != 0) {
                    return;
                }
                // 上传类型
                if (type == 2) {
                    this.followParam.enclosure.push({
                        // 显示地址
                        showUrl: element.name,
                        // 图片地址
                        url: res.data,
                    });
                }
                this.inputVal = null;
            });
        }
    }
    /**
     * 用户初始身份
     * @param state
    */
    temUserType_To_text(state: any) {
        let text = "";
        switch (parseInt(state)) {
            case 0:
                text = "未选择";
                break;
            case 1:
                text = "个人";
                break;
            case 2:
                text = "门店商户";
                break;
            case 3:
                text = "个人商户";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }

    /**
     * 用户真实身份
     * @param state
    */
    userType_To_text(state: any) {
        let text = "";
        switch (parseInt(state)) {
            case 0:
                text = "未选择";
                break;
            case 1:
                text = "个人";
                break;
            case 2:
                text = "门店商户";
                break;
            case 3:
                text = "个人商户";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }
    /**
     * 状态转换颜色
     */
    getStatusColor(s: any) {
        let colorText = "";
        switch (parseInt(s)) {
            // 橙色
            case 0:
                colorText = "font0"
                break;
            // 绿色
            case 1:
                colorText = "font1"
                break;

        }
        return colorText;
    }
    /**
     * 状态转文字
     * @param state
    */
    state_To_text(state: any) {
        let text = "";
        switch (parseInt(state)) {
            case 0:
                text = "无效";
                break;
            case 1:
                text = "有效";
                break;
            case 2:
                text = "禁用";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }

    // 粉丝
    showFansModal(item: any) {
        this.fansItems = item;
        this.fansModal.isFansVisible = true;
    }

    /**
     * 开启loading
     */
    createBasicMessage(): void {
        this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
    }
    /**
     * 移除loading
     */
    removeBasicMessage() {
        this.message.remove(this.messageId);
        this.messageId = null;
    }
    /**
     * 全局展示操作反馈信息
     * @param type 其他提示类型 success:成功 error:失败 warning：警告
     */
    createMessage(type: any, str: any): void {
        this.message.create(type, str);
    }

    addLabel(userId: any) {
        const modal = this.nzModalService.create({
            nzTitle: '用户打标',
            nzContent: UserLabelAddComponent,
            nzFooter: null,
            nzWidth: '400px',
            nzMaskClosable: false,
            nzComponentParams: {
                userId
            },
        });
        modal.afterClose.subscribe((res: any) => {
            if (res && res.refresh) {
                this.getCustomerList();
            }
        });
    }
}
